package com.hmdp;

import java.io.*;
import java.net.*;

public class TCPClient {
    public static void main(String[] args) {
        Socket socket = null;
        PrintWriter out = null;
        BufferedReader in = null;
        BufferedReader stdIn = null;

        try {
            // 连接到服务器，服务器地址为localhost，端口为12345
            String host = "zhenduan.52era.com";
            socket = new Socket(host, 9689);
            System.out.println("已连接到服务器");

            // 获取输入输出流
//            out = new PrintWriter(socket.getOutputStream(), true);
//            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            socket.getOutputStream().write(getClientInfo());
//            out.println(getClientInfo());
            System.out.println("已发送数据");
            // 读取服务器响应
            InputStream inputStream = socket.getInputStream();
            System.out.println("服务器响应: " + inputStream.read(new byte[1]));
        } catch (UnknownHostException e) {
            System.err.println("未知主机");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
                if (stdIn != null)
                    stdIn.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static byte[] getClientInfo() {
        String cLIENTNAME = null;
        cLIENTNAME = "{\"userid\":\"88910\",\"appid\":\"YDS-C60-Android\",\"sn\":\"YXVDIST20071025\",\"type\":\"SERVER_EMS12_YNDL_26\"}";
        int clientLength = cLIENTNAME.getBytes().length;
        int framelength = 2 + 4 + clientLength + 1;
        byte[] buffer = new byte[framelength];
        buffer[0] = 0x09;
        buffer[1] = 0x00;
        byte[] framelen = intToByteArray(framelength);
        System.arraycopy(framelen, 0, buffer, 2, framelen.length);
        byte[] clientbyte = cLIENTNAME.getBytes();
        System.arraycopy(clientbyte, 0, buffer, 6, clientbyte.length);
        byte crclen = 0;
        for (int i = 0; i < buffer.length; i++) {
            crclen += buffer[i];
        }
        buffer[buffer.length - 1] = crclen;
        return buffer;
    }
    /**
     * int-->byte
     */
    public static byte[] intToByteArray(final int integer) {
        int byteNum = (40 - Integer.numberOfLeadingZeros(integer < 0 ? ~integer
                : integer)) / 8;
        byte[] byteArray = new byte[4];

        for (int n = 0; n < byteNum; n++)
            byteArray[3 - n] = (byte) (integer >>> (n * 8));

        return (byteArray);
    }
}
